package com.login;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.login.LoginAlphaAdapter.LoginElement;
import com.login.io.FileIO;
import com.login.io.FileIO.XMLFileFormat;


import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Main List of Logins
 * @author VertigoSol
 *
 */
public class LoginListActivity extends ListActivity 
{
	private static final boolean DEBUG = false;
	
	private Dialog addDialog, editDialog;
	private HashMap<String, Vector<LoginElement>> mainData;
	private LoginAlphaAdapter adapter;
	private String key;
	private LoginElement le;
	
	 protected void onPause()
	 {
		 super.onPause();

			//close this one down
//			finish();
//			Intent intent = new Intent(getApplicationContext(), LockScreenActivity.class);
//			startActivity(intent);
			
	 }
	
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_list_layout);
        
        Bundle b = getIntent().getExtras();
        key = b.getString("KEY");
        
        if(key != null)
			try {
				mainData = parseString(FileIO.loadData(this, FileIO.FILE_NAME, key));
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(this, "Data Not Loaded: " + e.toString(), Toast.LENGTH_LONG).show();
			}
        
		if(mainData ==null)
			mainData = new HashMap<String, Vector<LoginElement>>();
			
		if(DEBUG)
		{
			for(int i=0; i < 26; i++)
			{
				String s = String.valueOf((char)(65 + (i-1)));
				Vector<LoginElement> le = new Vector<LoginElement>();
				for(int j=0; j< 5; j++)
				{
					le.add(new LoginElement(s, "test", "test"));
				}
				mainData.put(s, le);
			}
		}
		
        setListAdapter(adapter = new LoginAlphaAdapter(mainData)
        {
        	protected View getMainView(View convertView, boolean header, String textTop, String textCenter, String textBottom) 
        	{ 
        		View v = convertView;
        		
        		 TextView tt = null;
        		 TextView ct = null;
                 TextView bt = null;
        		
        		if (header) { 
        			v = getLayoutInflater().inflate( 
        					R.layout.login_row_header, null); 
        			
        			if(v != null)
        				((TextView)v).setText(textTop);
        		} 
        		else{
        			v = getLayoutInflater().inflate( 
        					R.layout.login_row, null); 
        			
        				tt = (TextView) v.findViewById(R.id.toptextleft);
        				ct = (TextView) v.findViewById(R.id.centertextleft);
        				bt = (TextView) v.findViewById(R.id.bottomtextleft);
        				
        				if(bt != null)
        					bt.setText(textBottom);
        				
        				if(ct != null)
        					ct.setText(textCenter);
        				
        				if(tt != null)
        					tt.setText(textTop);
        		}

        		 

        		return v; 
        	} 
        });
        
        addDialog = new Dialog(this);
        addDialog.setContentView(R.layout.add_login_layout);
        addDialog.setTitle("New Login");
        addDialog.setCancelable(true);
        
        final EditText newKey = (EditText) addDialog.findViewById(R.id.keyEdit);
        final EditText newValue = (EditText) addDialog.findViewById(R.id.valueEdit);
        final EditText newName = (EditText) addDialog.findViewById(R.id.nameEdit);
        
        Button button = (Button) addDialog.findViewById(R.id.addButtonDiag);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) 
            {
            	Vector<LoginElement> vv;
            	
            	String nameText = newName.getText().toString();
            	String keyText = newKey.getText().toString();
            	String valueText = newValue.getText().toString();
            	
            	if(keyText.isEmpty() || valueText.isEmpty())
            		return;
            	
            	char c = Character.toUpperCase(nameText.charAt(0));
            	
            	if(!Character.isLetter(c))
            	{
            		c = '#';
            	}
            	
            	if(mainData.containsKey(String.valueOf(c)))
            	{
            		vv = mainData.get(String.valueOf(c));
            	}
            	else
        		 vv= new Vector<LoginElement>();
            	
            	
        		vv.add(new LoginElement(nameText, keyText, valueText));
        		Collections.sort(vv);
        		mainData.put(String.valueOf(c), vv);
	    	
        		addDialog.dismiss();
        		
        		adapter.loadData(mainData);
        		adapter.notifyDataSetChanged();
            }
        });
        
        
        editDialog = new Dialog(this);
        editDialog.setContentView(R.layout.edit_login_layout);
        editDialog.setTitle("Edit Login");
        editDialog.setCancelable(true);
        
        final EditText newKey2 = (EditText) editDialog.findViewById(R.id.keyEdit2);
        final EditText newValue2 = (EditText) editDialog.findViewById(R.id.valueEdit2);
        final EditText newName2 = (EditText) editDialog.findViewById(R.id.nameEdit2);
        
        Button editButton =(Button) editDialog.findViewById(R.id.editButtonDiag);
        editButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) 
            {
            	String nameText = newName2.getText().toString();
            	String keyText = newKey2.getText().toString();
            	String valueText = newValue2.getText().toString();
            	
            	//TODO this is wrong have to shift to correct array
            	
            	le.name= nameText;
            	le.key = keyText;
            	le.value = valueText;
            	
				editDialog.dismiss();
				adapter.notifyDataSetChanged();
            }
        });
        
        Button delButton =(Button) editDialog.findViewById(R.id.deleteButtonDiag);
        delButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) 
            {
            	//TODO
            }
        });
        
        
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
        
			public boolean onItemLongClick(AdapterView<?> adap, View view,int position, long id) {
				le = (LoginElement) adapter.getItem(position);
				newKey2.setText(le.key);
				newName2.setText(le.name);
				newValue2.setText(le.value);
				editDialog.show();
				return true;
			}
		});
        
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.options_menu, menu);
	    return true;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.saveAction:
	    	 if(key != null)
	 			try {
	 				FileIO.saveData(this,FileIO.FILE_NAME ,createString(mainData) , key, false);
	 			} catch (Exception e) {
	 				Toast.makeText(this, "File Not Saved: " + e.getMessage(), Toast.LENGTH_LONG).show();	
	 				return true;
	 			}
	 		Toast.makeText(this, "File Saved ", Toast.LENGTH_SHORT).show();		
	 			
	        return true;
	    case R.id.addLogin:
	    	addDialog.show();
	        return true;
	    case R.id.exportAction:
	    	try {
				FileIO.saveData(this,FileIO.FILE_NAME_SD ,createString(mainData), key, true);
			} catch (Exception e) {
				Toast.makeText(this, "File Not Saved: " + e.getMessage(), Toast.LENGTH_LONG).show();	
 				return true;
			}
			
			Toast.makeText(this, "File Saved ", Toast.LENGTH_SHORT).show();
			
	        return true;
	        
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public HashMap<String, Vector<LoginElement>> parseString(String data)
	{
		String error =null;
		try {
			return XMLFileFormat.xmlToData(data);
		} catch (ParserConfigurationException e) {
			error = e.getMessage();
		} catch (SAXException e) {
			error = e.getMessage();
		} catch (IOException e) {
			error = e.getMessage();
		}
		
		Toast.makeText(this, "Error Loading Data: " + error, Toast.LENGTH_LONG).show();	
		
		return new HashMap<String, Vector<LoginElement>>();
	}
	
	public String createString(HashMap<String, Vector<LoginElement>> values)
	{
		return XMLFileFormat.dataToXML(values);
	}

}
